package com.jinhua.admin.service.impl;

import com.jinhua.admin.dao.OrderDao;
import com.jinhua.admin.entity.OrderPo;
import com.jinhua.admin.service.OrderService;
import com.jinhua.admin.vo.OrderVo;
import com.jinhua.config.BeanCopierUtil;
import com.jinhua.config.PaginationRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
* 订单表的service层
*
*/

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    private final long ERROR_LONG = 0L;
    private final int ERROR_INT = 0;
    @Autowired
    private OrderDao orderDao;
    @Transactional
@Override
    public long saveOrder(OrderVo orderVo) {
        if (orderVo == null) {
            log.warn("操作订单表参数为空");
            return ERROR_LONG;
        }
        OrderPo orderPo = orderVo.copyOrderPo();
        if (orderPo.getId() == null) {
            log.info("start添加订单表={}", orderPo);
            int result = orderDao.saveOrderIfNotExist(orderPo);
            return result != 0 ? orderPo.getId() : ERROR_LONG;
        }
        else {
            log.info("start修改订单表={}", orderPo.getId());
            return orderDao.modOrder(orderPo);
        }
    }
    @Override
    public int delOrderByIds(Long... ids) {
        if (ids == null || ids.length == 0) {
            log.warn("删除订单表,ids集合为空");
            return ERROR_INT;
        }
        log.warn("start删除Id集合={},订单表", Arrays.asList(ids));
        return orderDao.delOrderByIds(ids);
    }
    @Override
    public OrderVo findOrderById(Long id) {
        if (id == null||id<=0L) {
            log.warn("根据Id查找订单表,所传Id不符合规范");
            return new OrderVo();
        }
        log.info("start根据Id={}查找订单表", id);
        OrderPo orderPo = orderDao.findOrderById(id);
        return orderPo==null?new OrderVo():orderPo.copyOrderVo() ;
    }
    @Override
    public List<OrderVo> findOrderByAll(PaginationRequest<OrderVo> request) {
        List  <OrderVo> orderVos = new ArrayList<>();
        if (request == null) {
            log.warn("根据条件查找订单表,参数不对");
            return orderVos;
        }
        log.info("start根据条件查找订单表={}", request);
        try {
            List <OrderPo> orderPos = orderDao.findOrderByAll( request.getQueryCriteria().copyOrderPo(),request.getPageNum(),request.getPageSize());
            orderVos = BeanCopierUtil.copyList(orderPos,OrderPo.class, OrderVo.class);
        } catch (Exception e) {
            log.error("OrderServiceImpl.findOrderByAll error:{}",e.getMessage(), e);
            throw new RuntimeException(e);
        }
        return orderVos;
    }
}
